package com.pro01.backend.task;

import com.pro01.backend.mapper.UserMapper;
import com.pro01.backend.service.UserService;
import com.pro01.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserStatsRefreshTask {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    /**
     * 每30分钟刷新一次所有用户的 贡献值、虚拟分享率、等级
     */
    @Scheduled(fixedRate = 30 * 60 * 1000)  // 30分钟刷新一次（单位毫秒）
    public void refreshAllUserStats() {
        System.out.println("🌟 开始刷新所有用户的贡献值、等级、分享率...");

        List<User> users = userMapper.getAllUsers();
        for (User user : users) {
            try {
                userService.refreshCreditAndLevel(user.getId());
            } catch (Exception e) {
                System.err.println("❌ 刷新用户ID " + user.getId() + " 失败：" + e.getMessage());
            }
        }

        System.out.println("✅ 全部用户刷新完成！");
    }
}
